
Struct similar to class but a struct is a value type where class is a reference type. All the differences that are applicable to value and reference types are also applicable to classes and structs. Structs are stored on stack and classes are stored on the heap. Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory. Value types are destroyed after the scope is lost, where for reference type only the reference variable is destroyed after the scope is lost. The object is later destroyed by garbage collector. When you copy a struct into another struct, a new copy of the struct gets created and modifications on one struct will not affect the values contained by the other struct. Structs can’t have destructors, but classes can have destructors. Structs cannot have explicit parameter less constructor where as a class can. Struct can’t inherit from another class where as a class can, both structs and classes can inherit from an interface. Given bellow the example code and explain the code:
Note: A class or a struct can’t inherit from another struct. Struct are sealed types.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using testForClass1;
namespace testFor
{
public struct Student
{
private int _id;
private string _name;
public Student(int id, string name)
{
this._id = id;
this._name = name;
}
public int Id { get { return this._id; } set { this._id = value; } }
public string Name { get { return this._name; } set { this._name = value; } }
public void PrintDetels()
{
Console.WriteLine("Student Id:"+_id+" "+"Student Name : "+_name);
}
}
public class Program
{
static void Main(string[] args)
{
//use struct object and proparty
Student std = new Student();
std.Id = 101;
std.Name = "Farhan";
std.PrintDetels();
//use struct constructor
Student std2 = new Student(102,"Sakib");
std2.PrintDetels();
Console.Read();
}
}
}
In this code we create a struct name as Student, we write code like class then first we create object in struct under main method then set the value using property then call the PrintDetels method. Now under main method again create new object and call the constructor. This overloading constructor set the value then call the PrintDetels method.